import os
import wsgiref.handlers
from xml.dom import minidom

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

import urllib
from django.utils import simplejson

BASE_URL = "http://testdemo.appspot.com/"
TWITTER_TRENDS_URL = "http://search.twitter.com/trends/%s.json"
TWITTER_TRENDS_FORMATS = {'1':'current', '2':'daily', '3':'weekly', '4':'tag', '5':'user'}

class TwitterTrends(webapp.RequestHandler):
    """
    Accepts input digits from the caller, fetches twitter trends using the twitter api,
    and reads back the trends to the caller
    """
    def get(self):
        self.post()
    
    def _error(self, msg, redirecturl=None):
        templatevalues = {
            'msg': msg,
            'redirecturl': redirecturl
        }
        xml_response(self, 'error.xml', templatevalues)
    
    def post(self):
        choice = self.request.get('Choice') or '10'
        if not choice:
            self._error("Hey, you gave an invalid choice.", BASE_URL)
            return
        
	try:
		# strip off extra digits and keys from the Digits we got back
		choice = choice.replace('#', '').replace('*', '')[:1]
		choice = TWITTER_TRENDS_FORMATS[choice]
	except:
		choice = '1'
		choice = TWITTER_TRENDS_FORMATS[choice]		

        twitterTrendsUrl = TWITTER_TRENDS_URL % (choice)

        result = simplejson.load(urllib.urlopen(twitterTrendsUrl))
        ctime1 = result['as_of']
        ctime2 = result['trends'].keys()[0]
        trends = result['trends'].values()[0]

        if not trends:
            self._error("Error fetching weather. Good Bye.")
            return
        
        try:
	    count = len(trends)
	    trends_list = ', '.join(trend['name'].strip('#') for trend in trends)
            xml_response(self, 'trends.xml', { 'trends_list' : trends_list, 'current_time' : ctime2, 'count' : count })
	except:
            self._error("Error fetching twittertrends. Good Bye.")
            pass

def xml_response(handler, page, templatevalues=None):
    """
    Renders an XML response using a provided template page and values
    """
    path = os.path.join(os.path.dirname(__file__), page)
    handler.response.headers["Content-Type"] = "text/xml"
    handler.response.out.write(template.render(path, templatevalues))

class WelcomePage(webapp.RequestHandler):
    """
    Initial user greeting.
    Ask for the Option, and send the result to /twittertrends
    """
    def get(self):
        self.post()
    
    def post(self):
        templatevalues = {
            'postprefix': BASE_URL,
        }
        xml_response(self, 'menu.xml', templatevalues)

def main():
    application = webapp.WSGIApplication([ \
        ('/', WelcomePage),
        ('/twittertrends', TwitterTrends)],
        debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
